const express = require('express')
const history = require('connect-history-api-fallback') //处理前端路由history模式下页面404的错误
const expressJWT = require('express-jwt') //验证指定http请求的JsonWebTokens的有效性
const bodyParser = require('body-parser') //处理程序之前，在中间件中对传入的请求体进行解析
const fs = require('fs') //于与文件系统进行交互
const unless = require('express-unless')
const app = express()
const path = require('path')

app.use(require('cors')()) //处理跨域问题
app.use(express.json()) //Json转换
app.use(bodyParser.json()) //数据Json类型
app.use(bodyParser.urlencoded({
    extended: false
})) //解析post请求数据


//静态文件
// app.use('/', history({
//     index: '/index.html'
// }), express.static(path.join(__dirname, 'web')))

app.use('/admin', history({
    index: 'index.html'
}), express.static(path.join(__dirname, 'admin')))

app.use('/public', express.static(path.join(__dirname, 'public')))
app.use('/upload', express.static(path.join(__dirname, 'uploads')))


// //验证token
// const secretOrPrivateKey = "hello"  //加密token 校验token时要使用
// app.use(expressJWT({
//     secret: secretOrPrivateKey,
//     algorithms: ['HS256']
// }).unless({
//     path: ["/admin/api/login","/admin/api/createUser"]
// }))

//校验token失败时的处理
app.use((err, req, res, next) => {
    //前台直接展示不需要token
    if (req.originalUrl.slice(1, 4) == 'web') {
        return next()
    }
    if (err.name == 'UnauthorizedError') {
        res.status(err.status || 401).send({
            message: 'token失效，请重新登陆',
            code: 401,
            time: err.inner.expiredAt
        })
        return
    }
})

//全局方法
//fs.readdirSync(__dirname).filter(i => fileNames.includes(i))
// const fileNames = ['plugins','models']
// const global = fileNames.reduce((total, item) => {
//     const files = fs.readdirSync(__dirname + '/' + item)
//     files.map(i => {
//         let name = i.replace('.js', '')
//         let nameKey = i.replace('.js', '')
//         if(item == 'models'){
//             nameKey = name.replace(/^\S/, s => s.toUpperCase())
//         }
//         total[item][nameKey] = require(  __dirname + '/' + item + '/' +  name)
//     })
//     return total
// }, {'plugins': {}, 'models': {}})

// 加载所有路由
const router = express.Router()
const dirname = __dirname + '/routes'
fs.readdirSync(dirname).forEach((i) => {
    const file = dirname + '/' + i;
    if (fs.statSync(file).isDirectory()) {
        fs.readdirSync(file).forEach(item => {
            const name = item.replace('.js', '');
            //require( file + '/' + name )(app, global['plugins'], global['models'])
            require(file + '/' + name)(app, router)
        })
    }
})

require('./plugins/db')(app)


app.listen(3001, () => {
    console.log('在3001端口开启了一个服务');
})